package com.wva.servletcontext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 获取文件的真实(服务器)路径
 */
@WebServlet("/demo03ServletContext")
public class Demo03ServletContext extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 通过HttpServlet获取
    ServletContext context = this.getServletContext();

    // 获取文件的服务器路径
    String b = context.getRealPath("/b.txt");//webapp目录下资源访问
    System.out.println(b);
    // File file = new File(realPath);

    String c = context.getRealPath("/WEB-INF/c.txt");//webapp目录下WEB-INF目录下的资源访问
    System.out.println(c);

    String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
    System.out.println(a);


    //通过相对路径获取流对象
    Properties properties = new Properties();
    InputStream iStream = context.getResourceAsStream("/file/config.properties");  //通过相对路径获取流
    properties.load(iStream);
    System.out.println(properties.getProperty("name"));


    //通过路径获取流对象
    String realPath = context.getRealPath("/file/config.properties"); //webapp目录下的flie目录的资源访问
    Properties properties1 = new Properties();
    InputStream iStream1 = new FileInputStream(realPath);
    properties1.load(iStream1);
    System.out.println(properties1.getProperty("name"));

    //通过Classloader去获取工程下的资源,类加载器
    InputStream iStream2 = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
    Properties properties2 = new Properties();
    properties2.load(iStream2);
    // 3.获取属性的值
    String name = properties2.getProperty("name");
    System.out.println(name);
    iStream2.close();


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
